﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.VisualTree;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DynamicData;
using Material.Icons;
using SukiUI.Controls;
using System.ComponentModel;
using System.Threading.Tasks;

namespace SageKing.Desktop.Features.ControlsLibrary.LeftMenu;

public partial class LeftMenuViewModel : DesktopPageBase
{
    [ObservableProperty]
    public partial string SearchText { get; set; }

    public Action<SysMenu, object, RoutedEventArgs> ClickAction { get; set; }

    public List<SysMenu> sysMenus = new List<SysMenu>();
    public List<(bool, Visual)> sysMenusLst = new List<(bool, Visual)>();
    public StackPanel _menuRoot;

    public LeftMenuViewModel() : base("LeftMenu", MaterialIconKind.MenuLeft)
    {
        ClickAction = (a, b, c) =>
        {
            Console.WriteLine($"单击了：{a.Title}");
        };
    }

    public void InitMenu(SysMenu sysMenu, StackPanel menuRoot, int level)
    {
        if (sysMenu.Children.Count <= 0)
        {
            //添加控件
            var getItem = AddMenuItemNoChild(sysMenu, menuRoot, level);
            sysMenusLst.Add(new(false, getItem));
        }
        else
        {
            var getExpander = GetMenuItemExpander(sysMenu, level);

            sysMenusLst.Add(new(true, getExpander.Item1));

            menuRoot.Children.Add(getExpander.Item1);

            foreach (var menu in sysMenu.Children)
            {
                InitMenu(menu, getExpander.Item2, level + 1);
            }
        }
    }

    public void InitMenu(StackPanel menuRoot)
    {
        if (sysMenus.IsEmpty())
        {
            GenDemoMenu();
        }
        _menuRoot = menuRoot;
        foreach (SysMenu sysMenu in sysMenus)
        {
            InitMenu(sysMenu, menuRoot, 0);
        }
    }
    /// <summary>
    /// 有下级菜单
    /// </summary>
    /// <param name="sysMenu"></param>
    /// <param name="level"></param>
    /// <returns></returns>
    public (LeftMenuItemParentView, StackPanel) GetMenuItemExpander(SysMenu sysMenu, int level)
    {
        var ParentExpander = new LeftMenuItemParentView(level) { DataContext = sysMenu };

        var stackPanel = ParentExpander.GetStackPanel();

        return new(ParentExpander, stackPanel);
    }

    /// <summary>
    /// 无下级菜单
    /// </summary>
    /// <param name="sysMenu"></param>
    /// <param name="menuContent"></param>
    /// <param name="level"></param>
    public LeftMenuItemView AddMenuItemNoChild(SysMenu sysMenu, StackPanel menuContent, int level)
    {
        var itemNoChild = new LeftMenuItemView(level) { DataContext = sysMenu, ClickAction = ClickAction };
        menuContent.Children.Add(itemNoChild);
        return itemNoChild;
    }


    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);

        if (e.PropertyName == "SearchText")
        {
            FilterItems(SearchText);
        }
    }


    private void FilterItems(string search)
    {
        if (search.IsNullOrEmpty())
        {
            foreach (var item in sysMenusLst)
            {
                item.Item2.IsVisible = true;

                if (!item.Item1)
                {
                    continue;
                }

                (item.Item2 as LeftMenuItemParentView)?.Expanded(false);
            }
            return;
        }

        search = search.ToLower();

        foreach (var item in sysMenusLst)
        {
            var getMenu = item.Item2.DataContext as SysMenu;
            if (getMenu == null)
            {
                continue;
            }
            var header = getMenu.Title?.ToLower() ?? "";

            if (header.Contains(search))
            {
                item.Item2.IsVisible = true;
                ChangeParentToVisible(item.Item2);
            }
            else
            {
                item.Item2.IsVisible = false;
            }

        }

        List<Visual> childrenParent = sysMenusLst.Where(a => a.Item1 && a.Item2.IsVisible).Select(a => a.Item2).ToList();
        List<Visual> childrenChild = sysMenusLst.Where(a => !a.Item1 && a.Item2.IsVisible).Select(a => a.Item2).ToList();
        if (childrenParent.Count == 1 && childrenChild.Count <= 0)
        {
            ChangeChildToVisible(childrenParent.First());
        }

        foreach (LeftMenuItemParentView child in childrenParent)
        {
            child.Expanded(true);
        }
    }

    private void ChangeParentToVisible(Visual control)
    {
        if (control == null || control == _menuRoot) { return; }
        control.IsVisible = true;
        var gettopLevel = control.GetVisualParent();
        ChangeParentToVisible(gettopLevel);
    }

    private void ChangeChildToVisible(Visual control)
    {
        control.IsVisible = true;

        var gettopLevel = control.GetVisualChildren();
        if (!gettopLevel.HasItem())
        {
            return;
        }

        foreach (var child in gettopLevel)
        {
            child.IsVisible = true;
            ChangeChildToVisible(child);
        }

    }

    public void GenDemoMenu()
    {
        for (var i = 0; i < 10; i++)
        {
            var menu = new SysMenu() { Id = i, Title = "测试-A" + i };
            sysMenus.Add(menu);
        }

        foreach (var menu in sysMenus)
        {
            for (var i = 0; i < 10; i++)
            {
                var menu2 = new SysMenu() { Id = i, Title = "测试child-B" + menu.Id + "-" + i };
                if (menu.Children.IsEmpty())
                {
                    menu.Children = new List<SysMenu>();
                }
                menu.Children.Add(menu2);

                if (i % 2 == 0)
                {
                    for (var j = 0; j < 10; j++)
                    {
                        var menu3 = new SysMenu() { Id = j, Title = "测试child-C" + menu2.Id + "-" + j };
                        if (menu2.Children.IsEmpty())
                        {
                            menu2.Children = new List<SysMenu>();
                        }
                        menu2.Children.Add(menu3);
                    }
                }
            }
        }
    }
}
